import StringUtils from '../utils/StringUtils'
import Cookie from '../../static/js/cookie'

//JsApiTicket对象key
let jsApiTicketObjKey = "JsApiTicketObjKey";
//AccessToken对象key
let accessTokenObjKey = "AccessTokenObjKey";

export default {
    getConfig () {
        //1.获取公众号accessToken接口获取
        let accessTokenObj = this.getAccessTokenObj();
        if (accessTokenObj == null) {
            console.log("XWxConfig  accessTokenObj -- null")
            return null;
        }
        let appId = accessTokenObj.appId;
        let accessToken = accessTokenObj.token;
        // console.log("accessToken -- ", accessToken)
        //2.获取jsapi_ticket
        let jsApiTicket = this.getJsApiTicket(accessToken);
        // console.log("jsApiTicket -- ", jsApiTicket)
        //3.生成其他所需参数
        let norceStr = this.getRandomStr().toUpperCase();//生成签名的随机串
        let timestamp = parseInt(new Date().getTime() / 1000);//生成签名的时间戳
        let url = window.location.href.split('#')[0];
        let signature = this.genSign(jsApiTicket, norceStr, timestamp, url);       //签名
        let config = {
            "appId": appId,
            "timestamp": timestamp,
            "nonceStr": norceStr,
            "signature": signature,
            "debug": !!Cookie.getCookie('cF6HQCd643H55e23FddHWxdebug') || false,
            "jsApiList": ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareAppMessage', 'onMenuShareTimeline']
        };
        return config;
    },
    getJsApiTicket (accessToken) {
        let jsApiTicketStr = window.localStorage.getItem(jsApiTicketObjKey);
        if (StringUtils.isNotBlank(jsApiTicketStr)) {
            let jsApiTicketObj = JSON.parse(window.decodeURIComponent(jsApiTicketStr));
            if (jsApiTicketObj.expiresTime > new Date().getTime() + 5 * 60 * 1000) { //还有5分钟以上才过期
                return jsApiTicketObj.ticket;
            }
        }
        //请求接口获取
        if (StringUtils.isBlank(accessToken)) {
            return null;
        }
        let url = "/weixin_api/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi".replace("ACCESS_TOKEN", accessToken);
        let ticket = null;
        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            async: false,
            timeout: 10000,
            success: (response, textStatus, request) => {
                if (response.errcode == 0) {
                    let expiresTime = new Date().getTime() + response.expires_in * 1000;
                    ticket = response.ticket;
                    let jsApiTicketObj = {
                        "ticket": ticket,           //----票据
                        "expiresTime": expiresTime      //----过期時間戳(ms)
                    };
                    //保存到本地存储中
                    window.localStorage.setItem(jsApiTicketObjKey, window.encodeURIComponent(JSON.stringify(jsApiTicketObj)));
                    console.log('getJsApiTicket   ajax ticket : ', ticket)
                } else if (response.errcode == 40001) {//invalid credential, access_token is invalid or not latest hints: [3HBCJxPfe-wTmVvA!]
                    this.sleep(2000)
                    console.log('getJsApiTicket  sleep  2s')
                    return this.getJsApiTicket(url);
                }
            }
        });
        console.log('getJsApiTicket   result ticket : ', ticket)
        return ticket;
    },
    getAccessTokenObj () {
        let accessTokenStr = window.localStorage.getItem(accessTokenObjKey);
        if (StringUtils.isNotBlank(accessTokenStr)) {
            let accessTokenObj = JSON.parse(window.decodeURIComponent(accessTokenStr));
            if (accessTokenObj.expiresTime > new Date().getTime() + 5 * 60 * 1000) { //还有5分钟以上才过期
                return accessTokenObj;
            }
        }
        let url = '/nw_api/api/wechat/pub/access/token'
        let accessTokenObj = null
        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            async: false,
            timeout: 10000,
            success: (response, textStatus, request) => {
                if (response.success) {

                    accessTokenObj = {
                        "appId": response.result.appId,                  //----appId
                        "token": response.result.token,                  //----票据
                        "expiresTime": response.result.expiresTime      //----过期時間戳(ms)
                    };
                    //保存到本地存储中
                    window.localStorage.setItem(accessTokenObjKey, window.encodeURIComponent(JSON.stringify(accessTokenObj)));
                }
            }
        });
        return accessTokenObj;
    },
    getRandomStr () {
        let randomStr = ''
        for (let i = 0; i < 8; i++) {
            randomStr = randomStr + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return randomStr;
    },
    genSign (jsApiTicket, noncestr, timestamp, url) {
        //步骤1. 对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串string1
        let str = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
        //步骤2. 对string1进行sha1签名，得到signature：
        let signature = StringUtils.sha1(str);
        return signature;
    },
    sleep (ms) {
        return new Promise(resolve => setTimeout(resolve, ms))
    }
}
